package com.gitee.wsl.ext.set

import com.gitee.wsl.ext.collection.getByIndex


fun <T> MutableSet<T>.removeAt(index: Int):T {
    val value = this.getByIndex(index)
    remove(value)
    return value
}


/**
 * Removes values from the list as determined by the [predicate].
 * Generate an index-based loop that doesn't use an [Iterator].
 */
inline fun <T> MutableSet<T>.removeIfIndices(predicate: (T) -> Boolean) {
    var numDeleted = 0
    for (rawIndex in indices) {
        val index = rawIndex - numDeleted
        if (predicate(getByIndex(index))) {
            removeAt(index)
            numDeleted++
        }
    }
}

fun <E> MutableSet<E>.removeIf(filter: (E) -> Boolean): Boolean {
    var removed = false

    val each = iterator()
    while (each.hasNext()) {
        if (filter(each.next())) {
            each.remove()
            removed = true
        }
    }
    return removed
}

fun <T> MutableSet<T>.removeRange(start: Int, end: Int) {
    for (i in (end - 1) downTo start) {
        removeAt(i)
    }
}

inline fun <T> MutableSet<T>.removeFirstOrNull(predicate: (T) -> Boolean): T? {
    this.forEachIndexed { index, element ->
        if (predicate(element)) {
            return this.removeAt(index)
        }
    }
    return null
}

fun <T> MutableSet<T>.removeAfterIndex(afterIndex: Int) {
    while (this.size > afterIndex) {
        removeLast()
    }
}
